﻿using DotNetCore.CAP;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Wq.Extensions.Common;
using Wq.Extensions.Repository;
using Wq.ManagerService.Models;
using Wq.ManagerService;
using Wq.Model;

namespace Wq.Application
{
    /// <summary>
    /// 地区管理
    /// </summary>
    public class RegionApplication : BaseApplication
    {
        private readonly RegionService service;
        private readonly ICapPublisher capBus;
        private readonly RedisBaseRepository redisRepository;
        public RegionApplication(RegionService service, ICapPublisher capBus, RedisBaseRepository redisRepository)
        {
            this.service = service;
            this.capBus = capBus;
            this.redisRepository = redisRepository;
        }

        /// <summary>
        /// 获取下级集合
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<RegionData> Subs(int parentId) => service.Subs(parentId);

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public void Create(string name, int parentId)
        {
            service.Create(name, parentId);
            capBus.Publish(CAPKey.SaveRegionFile, "生成地址文件");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public void Save(int id, string name)
        {
            service.Save(id, name);
            capBus.Publish(CAPKey.SaveRegionFile, "生成地址文件");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Remove(long id)
        {
            if (service.Count(p => p.ParentId == id) > 0)
                throw new MyException("存在下级地区不能删除");
            service.DeleteById(id);
            capBus.Publish(CAPKey.SaveRegionFile, "生成地址文件");

        }

        /// <summary>
        /// 获取文件目录
        /// </summary>
        public string GetFile => OssManagement.REGION_SOURCE;


        /// <summary>
        /// 全部地区
        /// </summary>
        public List<RegionData> Data(int maxLevel = 4) => service.list(maxLevel);

        /// <summary>
        /// 获取层级关系地址
        /// </summary>
        /// <param name="data"></param>
        /// <param name="id"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        private List<RegionData> Regions(List<RegionData> data, long id = 0, int level = 4)
        {

            var list = data.Where(p => p.parentId == id).ToList();
            foreach (var item in list)
            {
                if (item.level < level)
                {
                    if (data.Where(p => p.parentId == item.id).Count() > 0)
                        item.items = Regions(data, item.id, level);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public List<RegionData> List(long id = 0, int level = 4) => redisRepository.Get(SysCacheKey.RegionToLevel(level), () => {
            var data = Data(level);
            return Regions(data, id, level);
        }).Result;



        /// <summary>
        /// 创建文件
        /// </summary>

        public void SaveFile()
        {
            var source = Regions(Data(4));
            var json = JsonConvert.SerializeObject(source);
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            AliyunOSSHelper.PutObject(OssManagement.REGION_SOURCE, stream);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public RegionDetails Details(long id)
        {
            var info = service.GetById(id);
            var details = info.Map<RegionDetails>();
            var FullIds = service.GetFullIds(id, ",").Trim(','); ;
            details.FullName = service.GetFullName(id);
            details.FullIds = FullIds.Split(",").Select(p => long.Parse(p)).ToList();
            return details;
        }

        /// <summary>
        /// 通过名称获取详情
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public RegionDetails DetailsByName(string name) => service.GetFirst(p => p.Name.Contains(name)).Map<RegionDetails>();
       
    }
}
